import React, { useState } from 'react';
import { Input, Button, List, Checkbox, Modal, Tabs, message, Form } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';

const { TabPane } = Tabs;

const TodoApp = () => {
    // 任务数据状态
    const [todos, setTodos] = useState([
        { id: 1, title: '学习 React 基础', completed: false },
        { id: 2, title: '掌握 Ant Design', completed: true },
        { id: 3, title: '实现任务筛选功能', completed: false },
    ]);

    const [currentTab, setCurrentTab] = useState('all'); // 筛选选项：all/active/completed
    const [isModalVisible, setIsModalVisible] = useState(false); // 控制编辑弹窗显示
    const [currentTodo, setCurrentTodo] = useState(null); // 当前编辑的任务
    const [form] = Form.useForm(); // 表单实例

    // 添加新任务
    const addTask = (value) => {
        if (!value.trim()) {
            message.warning('任务内容不能为空！');
            return;
        }
        const newTask = { id: Date.now(), title: value, completed: false };
        setTodos([...todos, newTask]);
        message.success('任务添加成功！');
    };

    // 切换任务完成状态
    const toggleComplete = (id) => {
        setTodos(todos.map((todo) => (todo.id === id ? { ...todo, completed: !todo.completed } : todo)));
    };

    // 删除任务
    const deleteTask = (id) => {
        setTodos(todos.filter((todo) => todo.id !== id));
        message.success('任务已删除！');
    };

    // 打开编辑任务弹窗
    const editTask = (todo) => {
        setCurrentTodo(todo);
        form.setFieldsValue({ title: todo.title });
        setIsModalVisible(true);
    };

    // 保存编辑任务
    const handleSaveEdit = () => {
        form.validateFields().then((values) => {
            setTodos(
                todos.map((todo) =>
                    todo.id === currentTodo.id ? { ...todo, title: values.title } : todo
                )
            );
            setIsModalVisible(false);
            setCurrentTodo(null);
            form.resetFields();
            message.success('任务已更新！');
        });
    };

    // 获取筛选后的任务列表
    const filteredTodos = todos.filter((todo) => {
        if (currentTab === 'active') return !todo.completed; // 仅活动任务
        if (currentTab === 'completed') return todo.completed; // 仅已完成任务
        return true; // 所有任务
    });

    return (
        <div style={{ maxWidth: 600, margin: '50px auto', padding: 24, background: '#fff', borderRadius: 8 }}>
            <h1 style={{ textAlign: 'center' }}>任务清单</h1>

            {/* 添加任务输入框 */}
            <Input.Search
                placeholder="输入新任务，按 Enter 或点击添加"
                enterButton={<PlusOutlined />}
                onSearch={addTask}
            />

            {/* Tabs 切换任务子集 */}
            <Tabs defaultActiveKey="all" onChange={(key) => setCurrentTab(key)} style={{ marginTop: 20 }}>
                <TabPane tab="所有任务" key="all" />
                <TabPane tab="仅活动任务" key="active" />
                <TabPane tab="仅已完成任务" key="completed" />
            </Tabs>

            {/* 任务列表 */}
            <List
                dataSource={filteredTodos}
                renderItem={(item) => (
                    <List.Item
                        actions={[
                            <Button
                                type="link"
                                icon={<EditOutlined />}
                                onClick={() => editTask(item)}
                                title="编辑"
                            />,
                            <Button
                                type="link"
                                icon={<DeleteOutlined />}
                                onClick={() => deleteTask(item.id)}
                                danger
                                title="删除"
                            />,
                        ]}
                    >
                        <Checkbox
                            checked={item.completed}
                            onChange={() => toggleComplete(item.id)}
                            style={{ marginRight: 10 }}
                        />
                        <span style={{ textDecoration: item.completed ? 'line-through' : 'none' }}>{item.title}</span>
                    </List.Item>
                )}
            />

            {/* 编辑任务弹窗 */}
            <Modal
                title="编辑任务"
                open={isModalVisible}
                onOk={handleSaveEdit}
                onCancel={() => {
                    setIsModalVisible(false);
                    form.resetFields();
                }}
            >
                <Form form={form} layout="vertical">
                    <Form.Item
                        name="title"
                        label="任务内容"
                        rules={[{ required: true, message: '请输入任务内容！' }]}
                    >
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default TodoApp;
